package it.cums.util;

import it.cums.model.Invoice;
import it.cums.model.Invoices;
import it.cums.model.Order;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class InvoiceManager {
	private static InvoiceManager invoiceManager;
	
	private InvoiceManager() {
	}
	
	public static InvoiceManager getInstance() {
		if (invoiceManager == null) {
			invoiceManager = new InvoiceManager();
		}
		return invoiceManager;
	}
	
	public void storeInvoices(Session session, Invoices invoices, Order order) throws Exception {
		deleteInvoices(session, order);
		insertInvoices(session, invoices);
	}
		
	@SuppressWarnings("unchecked")
	public List<Invoice> listInvoices(Order order) {
		Session session = null;
		Transaction tx = null;
		List<Invoice> invoices = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
		    tx = session.beginTransaction();
		    Query query = session.createQuery("from Invoice as i where i.order.id = :id order by i.id");
		    query.setInteger("id", order.getId());
		    invoices = query.list();
		    tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			HibernateUtil.rollback(tx);
		} finally {
			HibernateUtil.closeSession(session);
		}
		return invoices;
    }
	
	public void deleteInvoices(Session session, Order order) throws Exception {
		Query query = session.createQuery("delete Invoice i where i.order.id = :id");
		query.setInteger("id", order.getId());
		query.executeUpdate();
	}
	
	private void insertInvoices(Session session, Invoices invoices) throws Exception {
		for (Invoice invoice : invoices.getInvoices()) {
			session.save(invoice);
		}
	}
}